<?php
/**
 * SmsServ.php
 *
 * @copyright   2023 thingsworld.com.cn - All Rights Reserved
 * @link        http://thingsworld.com.cn/
 * @author      stiffer.chen <chenl@thingsworld.com.cn>
 * @created     2023-02-16 04:00:01
 * @modified    2023-02-16 04:00:01
 *
 */

namespace App\Services;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use App\Library\Logger;
use Darabonba\OpenApi\Models\Config;

class SmsServ
{
    private $log;
    private $accessKeyId = 'KUsx1StrJUcoXuk9';
    private $accessKeySecret = 'xB6RoFQtjmbL0PNpzO5JIdOTh4nHEw';
    private $signature = '嘉盛环境';
    private $endpoint = 'dysmsapi.aliyuncs.com';

    private $client = null;

    private $phone = '';

    public function __construct($phone)
    {
        $this->phone = $phone;

        $config = new Config([
            'accessKeyId' => $this->accessKeyId,
            'accessKeySecret' => $this->accessKeySecret
        ]);
        $config->endpoint = $this->endpoint;
        $this->client = new Dysmsapi($config);
        $this->log = new Logger('sms_ali');
    }

    public function send($code, $args)
    {
        $client = $this->client;
        $sendSmsRequest = new SendSmsRequest([
            'phoneNumbers' => $this->phone,
            'signName' => $this->signature,
            'templateCode' => $code,
            'templateParam' => $args
        ]);
        try {
            $response = $client->sendSmsWithOptions($sendSmsRequest, new RuntimeOptions([]));
            $this->log->info(var_export($response->body, true));
            $code = $response->body->code ?? '';
            if ($code != 'OK') {
                throw new \Exception($response->body->message);
            }
            $this->log->info("发送成功");
        } catch (\Exception $e) {
            $this->log->error($e->getMessage());
            throw new \Exception($e->getMessage());
        }
    }
}